<template>
  <view class="uploaddrive-warp">
    <!-- #ifdef H5 -->
    <van-nav-bar @click-left="onClickLeft" left-arrow title="上传行驶证"></van-nav-bar>
    <!-- #endif -->
    <view class="contain">
      <view class="uploaddrive-border">
        <view v-if="data.imagesA.length > 0">
          <block v-for="(item, index) in data.imagesA" :key="index">
            <view class="uploaddrive-index">
              <!-- 图片缩略图  -->
              <!-- <image
                class="q-image-wrap"
                :src="item"
                mode="scaleToFill"
                :data-idx="index"
                @tap="handleImagePreview"></image> -->
              <image class="q-image-wrap" :src="item" mode="scaleToFill" :data-idx="index"></image>
            </view>
          </block>
        </view>
        <view class="uploaddrive-index" v-else>
          <!-- <image
            class="q-image-wrap1"
            :src="`${resUrl}mine/front.png`"
            mode="scaleToFill"
            @tap="handleImagePreview"></image> -->
          <image class="q-image-wrap" :src="`${resUrl}mine/front.png`" mode="scaleToFill"></image>
        </view>
        <view class="chooseImage1" @tap="chooseImage" v-if="data.imagesA.length > 0">
          <view class="iconfont icon-camera"></view>
          <view class="rechoose">重新上传</view>
        </view>
        <view class="chooseImage" @tap="chooseImage" v-else>
          <text class="iconfont icon-camera"></text>
        </view>
      </view>
      <view class="text">
        <text style="color: #242424" decode="emsp" @tap="chooseImage">请上传行驶证正本照片</text>
      </view>
    </view>

    <view class="contain">
      <view class="uploaddrive-border">
        <view v-if="data.imagesB.length > 0">
          <block v-for="(item, index) in data.imagesB" :key="index">
            <view class="uploaddrive-index">
              <!-- 图片缩略图  -->
              <!-- <image
                class="q-image-wrap"
                :src="item"
                mode="scaleToFill"
                :data-idx="index"
                @tap="handleImagePreview1"></image> -->
              <image class="q-image-wrap" :src="item" mode="scaleToFill" :data-idx="index"></image>
            </view>
          </block>
        </view>
        <view class="uploaddrive-index" v-else>
          <!-- <image
            class="q-image-wrap"
            :src="`${resUrl}mine/reverse.png`"
            mode="scaleToFill"
            @tap="handleImagePreview1"></image> -->
          <image class="q-image-wrap" :src="`${resUrl}mine/reverse.png`" mode="scaleToFill"></image>
        </view>
        <view class="chooseImage1" @tap="chooseImage1" v-if="data.imagesB.length > 0">
          <view class="iconfont icon-camera"></view>
          <view class="rechoose">重新上传</view>
        </view>
        <view class="chooseImage" @tap="chooseImage1" v-else>
          <text class="iconfont icon-camera"></text>
        </view>
      </view>
      <view class="text">
        <text style="color: #242424" decode="emsp">请上传行驶证副本照片</text>
      </view>
    </view>
    <view class="bottom-wrap" :style="styleBntH">
      <button class="bnt-wrap bnt" @tap="sure">确认上传</button>
    </view>
    <!-- #ifdef H5 -->
    <PopupBtm ref="popupCameraRef" @set-item="chooseType" />
    <!-- #endif -->
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { getToken, getSystemInfo, systemInfo, setToastInstance } from '@mixins/info';
// #ifdef H5
import nativeApi from '@/mixins/nativeApi';
import PopupBtm from '@/components/popupBtm/popupBtm.vue';
// #endif
import { isAndroid } from '@/utils/util';
// #ifdef MP-WEIXIN
import { useToast } from '@/components/wxToast';
setToastInstance(useToast());
// #endif

const baseUrl = import.meta.env.VITE_VUE_APP_URL;
const $toast: any = inject('$Toast');
// 分享
onShareAppMessage(() => {
  return {
    title: '',
    path: '/pages/stationMap/stationMap',
  };
});

const resUrl = import.meta.env.VITE_VUE_APP_RES;

const styleBntH = `height: calc(124rpx + ${getSystemInfo().safeBottom}px)`;

const data = reactive({
  imagesA: [] as any,
  tempFilePathsA: [] as any,
  imagesB: [] as any,
  tempFilePathsB: [] as any,
  temdata: {
    brand: '',
    number: '',
    owner: '',
    type: '',
    url: '',
    vin: '',
  },
  temdataBack: null,
  chooseNum: '',
});
const popupCameraRef = ref();
const picFile = ref();
const popupCameraList = ref([
  {
    name: '拍照',
    type: 'camera',
  },
  {
    name: '相册',
    type: 'album',
  },
]);

const showLoading = () => {
  // #ifdef MP-WEIXIN
  // @ts-ignore
  wx.showLoading({
    title: '加载中',
  });
  // #endif

  // #ifndef MP-WEIXIN
  uni.showLoading({
    title: '加载中',
  });
  // #endif
};
const hideLoading = () => {
  // #ifdef MP-WEIXIN
  // @ts-ignore
  wx.hideLoading({
    noConflict: true,
  });
  console.log('hideLoading-------');
  // #endif
  // #ifndef MP-WEIXIN
  uni.hideLoading();
  // #endif
};
// #ifdef H5
const chooseType = (type: string) => {
  nativeApi
    .chooseImage({
      type,
    })
    .then((res: any) => {
      // console.log('获取原生图片', res);
      showLoading();
      const imgBase = `data:image/jpg;base64,${res.data}`;
      // 保存文件
      picFile.value = dataURLtoFile(imgBase, 'uploadDrive.jpeg');
      // // 检查文件大小
      checkFileSize(imgBase);
    })
    .catch((err: any) => {
      if (err.message === 'no-permission') {
        if (type === 'camera') {
          onCameraStorageForbidden();
        } else {
          onStorageForbidden();
        }
      } else {
        $toast(err.message);
      }
    });
};
/** 图片转换 */
const dataURLtoFile = (dataurl: any, filename: string) => {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  // 转换成file对象
  return new File([u8arr], filename, { type: mime });
};
/**
 * 校验文件是否大于5M
 */
const checkFileSize = (imgBase: any) => {
  const fileSize = (picFile.value.size / 1024 / 1024).toFixed(0);
  // console.log('this.picFile文件信息', this.picFile);
  if (Number(fileSize) > 5) {
    $toast('文件大于5M,请重新选择');
    return;
  }
  uploadToService(imgBase);
};
// #endif
/**
 * 上传图片到服务
 */
const uploadToService = (imgBase: any) => {
  const fileData = picFile.value;
  const sendData = new FormData();
  sendData.append('file', fileData);
  if (data.chooseNum === '0') {
    // 行驶证正面
    uni.uploadFile({
      url: baseUrl + '/api-server/ocr/ocrUpload',
      file: fileData,
      fileType: 'image', // 图片类型
      name: 'file',
      formData: {
        side: 'face',
      },
      header: {
        // 'Content-Type': 'application/json',
        encryptFlag: 'N',
        token: getToken(),
        channelId: import.meta.env.VITE_VUE_APP_CHANNEL,
      },
      success: resData => {
        console.log('resData', resData);
        hideLoading();
        data.temdata = JSON.parse(resData.data).data;
        if (!data.temdata) {
          $toast('行驶证正本照片识别失败，请重新上传!');
        } else {
          data.imagesA = [imgBase];
        }
      },
      fail(res) {
        hideLoading();
        console.log('失败');
        console.log(res);
        $toast('网络异常，请稍后重试！');
      },
    });
  } else if (data.chooseNum === '1') {
    // 行驶证副面
    uni.uploadFile({
      url: baseUrl + '/api-server/upload/img',
      file: fileData,
      fileType: 'image', // 图片类型
      name: 'file',
      header: {
        encryptFlag: 'N',
        token: getToken(),
        channelId: import.meta.env.VITE_VUE_APP_CHANNEL,
      },
      success: resData => {
        console.log('resData', resData);
        hideLoading();
        data.temdataBack = JSON.parse(resData.data).data;
        console.log(data.temdataBack);

        if (!data.temdataBack) {
          $toast('行驶证反面照片识别失败，请重新上传!');
        } else {
          data.imagesB = [imgBase];
        }
      },

      fail(res) {
        hideLoading();
        console.log('失败');
        console.log(res);
        $toast('网络异常，请稍后重试！');
      },
    });
  }
};
// #ifdef H5
const onCameraStorageForbidden = () => {
  if (isAndroid()) {
    uni.showModal({
      title: '温馨提示',
      content: '请在"设置">"隐私">"权限管理">"相册"、"存储"中允许使用',
      showCancel: true,
      confirmText: '去开启',
      success: (e: any) => {
        if (e.confirm) {
          nativeApi.go2Settings();
        }
      },
    });
  } else {
    nativeApi.go2Settings();
  }
};
const onStorageForbidden = () => {
  if (isAndroid()) {
    uni.showModal({
      title: '温馨提示',
      content: '请在"设置">"隐私">"权限管理">"存储"中允许使用',
      showCancel: true,
      confirmText: '去开启',
      success: (e: any) => {
        if (e.confirm) {
          nativeApi.go2Settings();
        }
      },
    });
  } else {
    nativeApi.go2Settings();
  }
};
// #endif

const chooseImage = (e: any) => {
  // #ifdef H5
  data.chooseNum = '0';
  popupCameraRef.value?.open(popupCameraList.value);
  // #endif
  // #ifndef H5
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    //可选择原图或压缩后的图片
    sourceType: ['album', 'camera'],
    //可选择性开放访问相册、相机
    success: res => {
      showLoading();
      uni.uploadFile({
        url: baseUrl + '/api-server/ocr/ocrUpload',
        filePath: res.tempFilePaths[0],
        name: 'file',
        formData: {
          side: 'face',
        },
        header: {
          'Content-Type': 'application/json',
          encryptFlag: 'N',
          token: getToken(),
          channelId: import.meta.env.VITE_VUE_APP_CHANNEL,
        },
        success: resData => {
          hideLoading();
          data.temdata = JSON.parse(resData.data).data;
          console.log(data.temdata);
          if (!data.temdata) {
            $toast('行驶证正本照片识别失败，请重新上传!');
          } else {
            const images11 = [...res.tempFilePaths];
            data.imagesA = images11;
            data.tempFilePathsA = res.tempFilePaths; //文件路径
          }
        },
        fail(res) {
          hideLoading();
          console.log('失败');
          console.log(res);
          $toast('网络异常，请稍后重试！');
        },
      });
    },
  });
  // #endif
};
// const handleImagePreview = (e: any) => {
//   const idx = e.target.dataset.idx;
//   const images = data.imagesA;
//   uni.previewImage({
//     current: images[idx],
//     //当前预览的图片
//     urls: images, //所有要预览的图片
//   });
// };

const chooseImage1 = (e: any) => {
  // #ifdef H5
  data.chooseNum = '1';
  popupCameraRef.value?.open(popupCameraList.value);
  // #endif
  // #ifndef H5
  uni.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    //可选择原图或压缩后的图片
    sourceType: ['album', 'camera'],
    //可选择性开放访问相册、相机
    success: res => {
      showLoading();
      uni.uploadFile({
        url: baseUrl + '/api-server/upload/img',
        filePath: res.tempFilePaths[0],
        name: 'file',
        header: {
          'Content-Type': 'application/json',
          encryptFlag: 'N',
          token: getToken(),
          channelId: import.meta.env.VITE_VUE_APP_CHANNEL,
        },
        success: resData => {
          hideLoading();
          data.temdataBack = JSON.parse(resData.data).data;
          console.log(data.temdataBack);

          if (!data.temdataBack) {
            $toast('行驶证反面照片识别失败，请重新上传!');
          } else {
            const images22 = [...res.tempFilePaths];
            data.imagesB = images22;
            data.tempFilePathsB = res.tempFilePaths; //文件路径
          }
        },

        fail(res) {
          hideLoading();
          console.log('失败');
          console.log(res);
          $toast('网络异常，请稍后重试！');
        },
      });
    },
  });
  // #endif
};
// const handleImagePreview1 = (e: any) => {
//   const idx = e.target.dataset.idx;
//   const images = data.imagesB;
//   uni.previewImage({
//     current: images[idx],
//     //当前预览的图片
//     urls: images, //所有要预览的图片
//   });
// };

const sure = () => {
  console.log('data.temdata===', data.temdata);
  if (data.temdata.url && data.temdataBack) {
    // if(data.temdata.url && !data.temdataBack)
    const brand = data.temdata.brand;
    const number = data.temdata.number;
    const owner = data.temdata.owner;
    const type = data.temdata.type;
    const url = data.temdata.url;
    const vin = data.temdata.vin;
    if (!brand || !number || !owner || !type || !url || !vin || !data.temdataBack) {
      $toast('驾驶证无法识别，请重新上传!');
    } else {
      console.log(
        `/pagesMyCenter/chargeCar/addCarUpload?temdataBack=${data.temdataBack}?data=` +
          JSON.stringify(data.temdata)
      );

      uni.navigateTo({
        url:
          `/pagesMyCenter/chargeCar/addCarUpload?temdataBack=${data.temdataBack}&&data=` +
          JSON.stringify(data.temdata),
      });
    }
  } else {
    $toast('请上传行驶证正本和行驶证副本照片');
    data.tempFilePathsA = [];
    data.tempFilePathsB = [];
  }
};

// #ifdef H5
const onClickLeft = () => {
  uni.navigateBack();
};
setTimeout(() => {
  const navBarEle = document.querySelector('.van-nav-bar') as HTMLElement;
  navBarEle.style.paddingTop = `${systemInfo.statusBarHeight}px`;
});
// #endif
</script>

<style lang="scss">
page {
  background-color: #f2f2f2;
}
</style>
<style lang="scss" scoped>
.uploaddrive-warp {
  .contain {
    width: 343px;
    height: 232px;
    border: 1px solid #ffffff;
    background-color: #ffffff;
    margin-top: 12px;
    display: flex;
    flex-flow: column;
    margin-left: auto;
    /* 块元素居中 */
    margin-right: auto;
    position: relative;
    border-radius: 5px;

    .uploaddrive-border {
      display: flex;
      flex-flow: column;
      margin-left: auto;
      /* 块元素居中 */
      margin-right: auto;
      width: 284px;
      height: 160px;
      border: 1px solid $uni-color-primary;
      border-radius: 12px;
      margin-top: 12px;
    }
  }

  .chooseImage {
    width: 56px;
    height: 56px;
    border-radius: 56px;
    background-color: rgba(0, 0, 0, 0.7);
    // position: relative;
    display: flex;
    align-items: center;
    align-self: center;
    justify-content: center;
    margin-top: 52px;
    z-index: 9;

    .iconfont {
      font-size: 22px;
      color: #fff;
    }
  }

  .chooseImage1 {
    margin-top: 68px;
    z-index: 9;
    text-align: center;

    .iconfont {
      font-size: 22px;
      color: #fff;
    }

    .rechoose {
      color: #fff;
      font-size: 14px;
      margin-top: 12px;
    }
  }

  .text {
    margin-top: 12px;
    display: flex;
    margin-left: auto;
    /* 块元素居中 */
    margin-right: auto;
    font-size: 18px;
    font-weight: 500;
    position: relative;
    z-index: 0;
  }

  .uploaddrive-index {
    position: absolute;
    z-index: 2;
  }

  .button-contain {
    position: absolute;
    bottom: 40rpx;
    width: 100vw;
  }

  .button {
    // background-image: var(--navBarBg);
    color: #fff;
    width: 40vw;
  }

  .q-image-wrap {
    float: left;
    margin-right: 10px;
    position: relative;
    // height: 400rpx;
    // width: 600rpx;
    width: 260px;
    height: 136px;
    padding: 12px;
  }

  .q-image-wrap1 {
    float: left;
    position: relative;
    width: 272px;
    height: 158px;
    border-radius: 5px;
  }

  .q-image-remover {
    width: 100rpx;
    height: 100rpx;
    border-radius: 100%;
    background: #00a6ff;
    position: absolute;
    top: -50rpx;
    right: -50rpx;
  }

  .q-image-remover icon {
    position: absolute;
    left: 12rpx;
    bottom: 12rpx;
    color: #fff;
  }

  .delete-btn {
    position: absolute;
    top: 0;
    right: 0;
    color: #00a6ff;
  }
}

.bottom-wrap {
  display: flex;
  position: fixed;
  width: 100%;
  bottom: 0;
  background: #fff;
  border-top: 1px solid #f2f2f2;
  box-sizing: border-box;

  .bnt {
    height: 44px;
    width: 343px;
    margin-top: 9px;
    border-radius: 50px;
  }
}
</style>